package org.darcy.service.privilege.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.darcy.dao.privilege.SysUserDataRangeMapper;
import org.darcy.entity.privilege.SysUserDataRange;
import org.darcy.framework.generic.GenericServiceImpl;
import org.darcy.framework.model.PageData;
import org.darcy.framework.model.PageParam;
import org.darcy.service.privilege.SysUserDataRangeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * SysUserDataRange服务实现
 */
@Service
@Transactional
public class SysUserDataRangeServiceImpl extends GenericServiceImpl<SysUserDataRange>
		implements SysUserDataRangeService {

	@Autowired
	private SysUserDataRangeMapper mapper;

	@Override
	public SysUserDataRange getDetail(Integer id) {
		SysUserDataRange record = mapper.selectById(id);
		return record;
	}

	@Override
	public PageData<SysUserDataRange> page(PageParam<SysUserDataRange> param) {
		IPage<SysUserDataRange> queryPage = new Page<SysUserDataRange>(param.getQuery().getPageNum(),
				param.getQuery().getPageSize());
		IPage<SysUserDataRange> data = mapper.getPage(queryPage, param.getEntity());
		for (SysUserDataRange a : data.getRecords()) {
			List<String> list = Arrays.asList(a.getDeptName().split(","));
			a.setDeptNameList(list);
		}
		PageData<SysUserDataRange> pageData = new PageData<SysUserDataRange>(data, param);
		return pageData;
	}

	@Override
	public List<SysUserDataRange> getList(Integer uid) {
		LambdaQueryWrapper<SysUserDataRange> params = new LambdaQueryWrapper<SysUserDataRange>();
		params.eq(SysUserDataRange::getUserId, uid);
		List<SysUserDataRange> list = super.getList(params);
		return list;
	}

	@Override
	public List<Integer> getDeptIdList(Integer uid) {
		List<SysUserDataRange> list = this.getList(uid);
		Set<String> deptIdSet = new HashSet<String>();
		for (SysUserDataRange a : list) {
			// 管理员，不筛选，返回全部
			if (a.getRoleId() == 1) {
				deptIdSet = null;
				break;
			}
			if (a.getRoleId() == 2) {
				deptIdSet.addAll(Arrays.asList(a.getDeptId().split(",")));
			}
			if (a.getRoleId() == 3) {
				deptIdSet.add(a.getDeptId());
			}
		}
		if (deptIdSet == null) {
			return null;
		}
		List<Integer> result = new ArrayList<Integer>();
		for (String a : deptIdSet) {
			result.add(Integer.parseInt(a));
		}
		return result;
	}

}
